﻿using FPSO.HMI.Utils;
using FPSO.Models.Constant;
using FPSO.Models.Domain;
using FPSO.Models.ViewModel.Controls;
using FPSO.Services;
using FPSO.Services.Impl;
using MySql.Data.MySqlClient;
using Opc.Ua;
using OpcUaHelper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Protocols.WSTrust;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Linq;

namespace FPSO.HMI.Views.Dialog
{
    public partial class UCValveDialog : Window
    {
        private UCValveViewModel viewModel;
		private List<OPCTag> opcTags = new List<OPCTag>();
        public UCValveDialog(string name,List<OPCTag> tags)
        {
            InitializeComponent();
            viewModel = new UCValveViewModel();
            this.DataContext = viewModel;
            viewModel.ValveName = name;
			opcTags = tags;

			initValveData();
			SetValveStatus();
            SetDeviceStatus();
        }

        /// <summary>
        /// Debug 在这里根据viewModel.ValveName进行取值显示操作
        /// </summary>
        private void initValveData()
        {
            // 随机生成阀门状态0：远程，1：本地手动，2：本地自动
            viewModel.ValveStatus = 1;
			// 随机生成设备状态0：关闭，1：开启，2：正在关闭，3：正在开启，4：故障
			int deviceStatus = 4;
			try
			{
				foreach (OPCTag tag in opcTags)
				{
					string opcname = tag.OpcName;
					bool status = Convert.ToBoolean(tag.OpcValue.Value);

					//当opctag的值不为0时，对应的状态标签起作用
					if (status)
					{
						if (opcname.Contains("StatusFault"))
						{
							deviceStatus = 4;
							CommUtil.AddSystemLog(5, 0, opcname);
						}
						else if (opcname.Contains("SCM_Open"))
						{
							deviceStatus = 3;
						}
						else if (opcname.Contains("SCM_Close"))
						{
							deviceStatus = 2;
						}
						else if (opcname.Contains("StatusOpened"))
						{
							deviceStatus = 1;
						}
						else if (opcname.Contains("StatusClosed"))
						{
							deviceStatus = 0;
						}
						break;
					}
				}
			}
			catch (Exception ex)
			{
				CommUtil.AddSystemLog(0, 2, ex.Message);
			}


			viewModel.DeviceStatus = deviceStatus;
            // 随机百分比数值0%-100%
            viewModel.ValveValue = 0/*RandomUtil.GetDoubleNumber(0, 100, 2)*/;
        }

        /// <summary>
        /// 设置阀门状态
        /// 0：远程，1：本地手动，2：本地自动
        /// </summary>
        private void SetValveStatus()
        {
            vavleStatus0.Background = Get_Status_Color(false);
            vavleStatus1.Background = Get_Status_Color(false);
            vavleStatus2.Background = Get_Status_Color(false);
            if (viewModel.ValveStatus == 0)
            {
                vavleStatus0.Background = Get_Status_Color(true);
            }
            if (viewModel.ValveStatus == 1)
            {
                vavleStatus1.Background = Get_Status_Color(true);
            }
            if (viewModel.ValveStatus == 2)
            {
                vavleStatus2.Background = Get_Status_Color(true);
            }
        }

        /// <summary>
        /// 设置设备状态
        /// 0：关闭，1：开启，2：正在关闭，3：正在开启，4：故障
        /// </summary>
        private void SetDeviceStatus()
        {
            deviceStatus0.Background = Get_Status_Color(false);
            deviceStatus1.Background = Get_Status_Color(false);
            deviceStatus2.Background = Get_Status_Color(false);
            deviceStatus3.Background = Get_Status_Color(false);
            deviceStatus4.Background = Get_Status_Color(false);
            if (viewModel.DeviceStatus == 0)
            {
                deviceStatus0.Background = Get_Status_Color(true);
            }
            if (viewModel.DeviceStatus == 1)
            {
                deviceStatus1.Background = Get_Status_Color(true);
            }
            if (viewModel.DeviceStatus == 2)
            {
                deviceStatus2.Background = Get_Status_Color(true);
            }
            if (viewModel.DeviceStatus == 3)
            {
                deviceStatus3.Background = Get_Status_Color(true);
            }
            if (viewModel.DeviceStatus == 4)
            {
                deviceStatus4.Background = Get_Status_Color(true);
            }
        }

        /// <summary>
        /// 退出事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            //返回false以阻止后续流程并退出 
            this.DialogResult = false;
        }



        /// <summary>
        /// 窗口拖动事件
        /// </summary>
        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                DragMove();
            }
        }

        /// <summary>
        /// 阀门打开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValveOpen_Click(object sender, RoutedEventArgs e)
		{
			//当阀门是关闭或者正在关闭时可以下发开启命令
			if (viewModel.DeviceStatus == 0 || viewModel.DeviceStatus == 2)
			{
				foreach(OPCTag tag in opcTags)
				{
					string tagname = tag.OpcName;
					//NOTICE : 区分实船场景和模拟场景
					//if (tagname.Contains("SCM_Open"))
					//{
					//	string cmd_tag1 = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, tagname);
					//	try
					//	{
					//		Open_Btn.Background = Get_Status_Color(false);
					//		App.UaClient.WriteNode<Int16>(cmd_tag1, 1);
					//	}
					//	catch (Exception ex)
					//	{
					//		CommUtil.AddSystemLog(0, 1, ex.Message);
					//	}
					//	return;
					//}
					if(tagname.Contains("StatusOpened"))
					{
						string cmd_tag1 = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, tagname);
						try
						{
							Open_Btn.Background = Get_Status_Color(false);
							App.UaClient.WriteNode<Int32>(cmd_tag1, 1);
						}
						catch (Exception ex)
						{
							CommUtil.AddSystemLog(0, 1, ex.Message);
						}
					}
					else if(tagname.Contains("StatusClosed"))
					{
						string cmd_tag1 = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, tagname);
						try
						{
							App.UaClient.WriteNode<Int32>(cmd_tag1, 0);
						}
						catch (Exception ex)
						{
							CommUtil.AddSystemLog(0, 1, ex.Message);
						}
					}
				}
			}
		}

        /// <summary>
        /// 阀门关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValveClose_Click(object sender, RoutedEventArgs e)
        {
			if (viewModel.DeviceStatus == 1 || viewModel.DeviceStatus == 3)
			{
				foreach (OPCTag tag in opcTags)
				{
					string tagname = tag.OpcName;
					//NOTICE : 区分实船场景和模拟场景
					//if (tagname.Contains("SCM_Close"))
					//{
					//	string cmd_tag1 = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, tagname);
					//	try
					//	{
					//		Close_Btn.Background = Get_Status_Color(false);
					//		App.UaClient.WriteNode<Int16>(cmd_tag1, 1);
					//	}
					//	catch (Exception ex)
					//	{
					//		CommUtil.AddSystemLog(0, 1, ex.Message);
					//	}
					//	return;
					//}
					if (tagname.Contains("StatusOpened"))
					{
						string cmd_tag1 = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, tagname);
						try
						{
							Open_Btn.Background = Get_Status_Color(false);
							App.UaClient.WriteNode<Int32>(cmd_tag1, 0);
						}
						catch (Exception ex)
						{
							CommUtil.AddSystemLog(0, 1, ex.Message);
						}
					}
					else if (tagname.Contains("StatusClosed"))
					{
						string cmd_tag1 = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, tagname);
						try
						{
							App.UaClient.WriteNode<Int32>(cmd_tag1, 1);
						}
						catch (Exception ex)
						{
							CommUtil.AddSystemLog(0, 1, ex.Message);
						}
					}
				}
			}
		}


        /// <summary>
        /// 获取状态颜色
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private SolidColorBrush Get_Status_Color(bool status)
        {
            return status
                ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#50d000"))
                : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#c6e0b6"));
        }
    }
}
